package com.sea.base.widget

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import androidx.customview.widget.ViewDragHelper
import kotlin.math.max
import kotlin.math.min

/**
 * 悬浮球父布局 可支持子View的拖动
 */
class FloatingSuspensionLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
    /**
     * 当手指释放后 页面显示子View宽度的百分比
     */
    var showViewPercent = 1f

    private val viewDragHelper = ViewDragHelper.create(this, 1.0f, object : ViewDragHelper.Callback() {
        override fun tryCaptureView(child: View, pointerId: Int) = true

        /**
         * 边界拖动范围
         */
        override fun getViewHorizontalDragRange(child: View) = measuredWidth - child.measuredWidth

        override fun getViewVerticalDragRange(child: View) = measuredHeight - child.measuredHeight

        override fun clampViewPositionHorizontal(child: View, left: Int, dx: Int): Int {
            val leftBound = paddingLeft
            val rightBound: Int = width - child.width - leftBound
            return min(rightBound, max(left, leftBound))
        }

        override fun clampViewPositionVertical(child: View, top: Int, dy: Int): Int {
            val topBound = paddingTop
            val bottomBound: Int = height - child.height - topBound
            return min(bottomBound, max(top, topBound))
        }

        /**
         * 手指释放的时候回调
         */
        override fun onViewReleased(releasedChild: View, xvel: Float, yvel: Float) {
            var mY: Int = releasedChild.top
            if (releasedChild.top < 0) {
                mY = 0
            }
            if (releasedChild.bottom > height) {
                mY = height - releasedChild.measuredHeight
            }
            if (releasedChild.right - releasedChild.measuredWidth / 2 > width / 2) {
                settleCapturedViewAt((width - releasedChild.width * showViewPercent).toInt(), mY)
            } else {
                settleCapturedViewAt((0 - releasedChild.width * (1 - showViewPercent)).toInt(), mY)
            }
            invalidate()
        }
    })

    private fun settleCapturedViewAt(finalLeft: Int, finalTop: Int) {
        viewDragHelper.settleCapturedViewAt(finalLeft, finalTop)
    }

    override fun onInterceptTouchEvent(event: MotionEvent) = viewDragHelper.shouldInterceptTouchEvent(event)

    override fun onTouchEvent(event: MotionEvent): Boolean {
        viewDragHelper.processTouchEvent(event)
        return false
    }

    override fun computeScroll() {
        if (viewDragHelper.continueSettling(true)) {
            invalidate()
        }
    }

    /**
     * 里面的子View需要消费对应的事件
     */
    override fun onViewAdded(child: View) {
        super.onViewAdded(child)
        child.isClickable = true
    }
}